package com.ys.考试;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述:  使用map 存储数据, 使用ObjectStream io来持久化 map
 *
 * @author CodeYang
 * @version 2021/1/20 21:34
 */
public class 集合02 {


    public static void main(String[] args) {

        // 1创建 HashMap
        HashMap<Object, Student> map = new HashMap<>(32);
        Student[] students ={
                new Student(101, "ys1", 128),
                new Student(102, "ys2", 183),
                new Student(103, "ys3", 201)
        };

        for (Student student : students) {
            map.put(student.getId(),student);
        }


        // 开启IO
        try {
            File file = new File("map.txt");
            //用对象流来持久化数据 写
            ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(file));
           out.writeObject(map);
           out.flush();
           out.close();
           // 对象流读
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
            HashMap<Integer,Student> map2 = new HashMap<>(32);
            map2 = (HashMap<Integer, Student>) in.readObject();
            in.close();
            for (Map.Entry<Integer, Student> mapObj : map2.entrySet()) {
                System.out.println(mapObj);
            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }

}
